package com.walnut.dao.impl;

import com.walnut.dao.UserDao;
import com.walnut.pojo.User;
import com.walnut.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public boolean login(User user) throws SQLException {
        Connection conn = DBUtil.getConnection();
        String sql = "select count(*) as ct from user where username=? and password=?";

        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setString(1, user.getUsername());
        pst.setString(2, user.getPassword());
        ResultSet rs = pst.executeQuery();
        rs.next();

        int ct = rs.getInt("ct");
        rs.close();

        if(ct == 1)
            return true;

        return false;
    }

    @Override
    public List<User> select() {
        return List.of();
    }

    @Override
    public User selectByName(String username) throws SQLException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE username = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);

            rs = pstmt.executeQuery();

            if (rs.next()) {  // 检查是否有记录
                User user = new User().builder()
                        .userid(rs.getInt("user_id"))
                        .username(rs.getString("username"))
                        .password(rs.getString("password"))
                        .email(rs.getString("email"))
                        .phone(rs.getLong("phone"))
                        .isAdmin(rs.getInt("is_admin"))
                        .build();
                return user;
            }
        } finally {
            rs.close();
            conn.close();
            pstmt.close();
        }

        return null;  // 如果结果集为空，返回 null
    }

    @Override
    public User selectById(Integer userId) {
        return null;
    }

    @Override
    public int insert(User user) throws SQLException{
        Connection conn = DBUtil.getConnection();
        PreparedStatement pstmt = null;
        String sql = "insert into user (username,password,email,phone,is_admin) values (?,?,?,?,?)";

        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, user.getUsername());
        pstmt.setString(2, user.getPassword());
        pstmt.setString(3, user.getEmail());
        pstmt.setLong(4, user.getPhone());
        pstmt.setInt(5, 0);
        int count=pstmt.executeUpdate();
        return count;
    }

    @Override
    public int update(User user) {
        return 0;
    }

    @Override
    public int delete(Integer userId) {
        return 0;
    }
}
